package com.ruoyi.framework.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
@Component
public class BaseMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {

        if(metaObject.hasSetter("createBy")){
            try {

                metaObject.setValue("createBy",null);
                this.strictInsertFill(metaObject, "createBy", String.class, SecurityUtils.getUsername());

            }catch (Exception e){
                this.strictInsertFill(metaObject, "createBy", String.class, "");
            }
        }

        if(metaObject.hasSetter("createTime")){
            metaObject.setValue("createTime",null);
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        }

        if(metaObject.hasSetter("companyCod")){

            if(StringUtils.isNull(metaObject.getValue("companyCod"))){
                this.strictInsertFill(metaObject, "companyCod", String.class, SecurityUtils.getCompanyCode());
            }

        }

        if(metaObject.hasSetter("createAt")){
            metaObject.setValue("createAt",null);
            this.strictInsertFill(metaObject, "createAt", Date.class, new Date());
        }

        if(metaObject.hasSetter("updateAt")){
            metaObject.setValue("updateAt",null);
            this.strictInsertFill(metaObject, "updateAt", Date.class, new Date());
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(metaObject.hasSetter("updateBy")){
            try {
                metaObject.setValue("updateBy",null);
                this.strictUpdateFill(metaObject,"updateBy",String.class,SecurityUtils.getUsername());
            }catch (Exception e){
                this.strictUpdateFill(metaObject,"updateBy",String.class,"");
            }
        }

        if(metaObject.hasSetter("updateTime")){
//            System.out.println(DateUtils.getTime());
            metaObject.setValue("updateTime",null);
            this.strictUpdateFill(metaObject,"updateTime",Date.class,new Date());
        }

        if(metaObject.hasSetter("updateAt")){
            metaObject.setValue("updateAt",null);
            this.strictUpdateFill(metaObject, "updateAt", Date.class, new Date());
        }

    }
}
